﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using XXX.api.Auth;
using XXX.Bo;

namespace XXX.api.Controllers
{
    [Route("api/oauth")]
    [ApiController]
    public class OAuthController : ControllerBase
    {
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("token")]
        public Models.RetModel GetAccessToken(string username, string password)
        {
            Models.RetModel retModel = new Models.RetModel();

            //这儿在做用户的帐号密码校验。我这儿略过了。
            int bCheck = 0;


            if (username == "admin" && password == "admin")
            {
                bCheck = 1;
            }
            else if (username == "wanhua" && password == "whpwd")
            {
                bCheck = 1;

            }
            else
            {
                bCheck = JinTongUser.checkuser(username, password);
            }


            if (bCheck == 0)
            {
                retModel.code = 101;
                retModel.message = "账号密码不正确";
                return retModel;
            };

            var claims = new[]
            {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, ""),
        };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(TokenParameter.Issuer, TokenParameter.Audience, claims, expires: DateTime.UtcNow.AddMinutes(TokenParameter.AccessExpiration), signingCredentials: credentials);
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            retModel.code = 200;
            retModel.message = token;
            return retModel;
        }
    }
}
